import React, { Component } from 'react';
import './practice.scss';
import PrChild from './PrChild1';
import PrChild2 from './PrChild2';
import { globalContext } from './global';
const { Provider } = globalContext;
class Practice extends Component {
  // createRef调用后返回一个容器，该容器可以存放被ref表示的节点，一个容器只能供一个ref使用;
  myRef = React.createRef();
  myRef1 = React.createRef();
  state = {
    data1: '父组件传过来的数据',
    name: '张楠',
    email: '2727557082@qq.com',
    updateName: (val) => {
      this.setState(() => ({
        name: val,
      }));
    },
  };
  updateData1 = (value) => {
    this.setState({
      data1: value,
    });
  };
  // 第一个input框
  onInput1 = () => {
    //  字符串ref
    // alert(this.refs.input1.value);
    // 回调ref
    // alert(this.input1.value);
    // createRef Api
    alert(this.myRef.current.value);
  };
  // 第二个input框
  onInput2 = () => {
    // 字符串ref
    // alert(this.refs.input2.value);
    // 回调ref
    // alert(this.input2.value);
    // createRef Api
    alert(this.myRef1.current.value);
  };
  // ref指定回调
  saveInput = (e) => {
    this.input2 = e;
  };
  render() {
    console.log(this, '父组件');
    return (
      <div className="practice">
        <h1>组件练习(ref获取dom的三种方法,组件传值) 父组件</h1>
        <div className="input111">
          <h2>字符串ref</h2>
          <input ref="input1" type="text" placeholder="input1" />
          <button>点我alert弹出input1的数据</button>
          <input ref="input2" type="text" placeholder="input2" />
        </div>
        <div className="huidiaoref">
          <h2>回调ref</h2>
          {/* 内联函数 */}
          <input
            ref={(c) => (this.input1 = c)}
            type="text"
            placeholder="input1"
          />
          <button>点我alert弹出input1的数据</button>
          {/* 指定回调 */}
          <input ref={this.saveInput} type="text" placeholder="input2" />
        </div>
        <div className="createref">
          <h2>createRef Api</h2>
          <input ref={this.myRef} type="text" placeholder="input1" />
          <button onClick={this.onInput1}>点我alert弹出input1的数据</button>
          <input
            ref={this.myRef1}
            type="text"
            onBlur={this.onInput2}
            placeholder="input2"
          />
        </div>
        <Provider value={this.state}>
          {/* 子组件一 */}
          <PrChild
            ref="child1"
            data1={this.state.data1}
            updateData1={this.updateData1}
          />
          {/* 子组件二 */}
          <PrChild2 />
        </Provider>
      </div>
    );
  }
}

export default Practice;
